const db = require('../config/database');

class News {
    static async create(newsData) {
        const { title, content, reporter_name } = newsData;
        const [result] = await db.execute(
            'INSERT INTO news (title, content, reporter_name) VALUES (?, ?, ?)',
            [title, content, reporter_name]
        );
        return result.insertId;
    }

    static async findById(id) {
        const [rows] = await db.execute('SELECT * FROM news WHERE news_id = ?', [id]);
        return rows[0];
    }

    static async getAll(page = 1, limit = 10) {
        const offset = (page - 1) * limit;
        const [rows] = await db.query(
            'SELECT * FROM news ORDER BY publish_time DESC LIMIT ? OFFSET ?',
            [limit, offset]
        );
        return rows;
    }

    static async update(id, newsData) {
        const { title, content, reporter_name } = newsData;
        const [result] = await db.execute(
            'UPDATE news SET title = ?, content = ?, reporter_name = ? WHERE news_id = ?',
            [title, content, reporter_name, id]
        );
        return result.affectedRows > 0;
    }

    static async delete(id) {
        const [result] = await db.execute('DELETE FROM news WHERE news_id = ?', [id]);
        return result.affectedRows > 0;
    }

    static async updateCounts(newsId, field) {
        const validFields = ['read_count', 'like_count', 'comment_count'];
        if (!validFields.includes(field)) return false;
        
        const [result] = await db.execute(
            `UPDATE news SET ${field} = ${field} + 1 WHERE news_id = ?`,
            [newsId]
        );
        return result.affectedRows > 0;
    }
}
//11
module.exports = News; 